package cn.daniellee.plugin.wc.listener;

import cn.daniellee.plugin.wc.Welcome;
import cn.daniellee.plugin.wc.core.WelcomeCore;
import cn.daniellee.plugin.wc.model.PlayerData;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public class BungeeListener implements PluginMessageListener {

	@Override
	public void onPluginMessageReceived(String s, Player player, byte[] bytes) {
		ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
		String subChannel = in.readUTF();
		if ("Welcome".equals(subChannel)) {
			short length = in.readShort();
			byte[] msgBytes = new byte[length];
			in.readFully(msgBytes);
			DataInputStream msgIn = new DataInputStream(new ByteArrayInputStream(msgBytes));
			try {
				String msg = msgIn.readUTF();
				if ("Newbie".equals(msg)) {
					String name = msgIn.readUTF();
					long joinDate = msgIn.readLong();
					PlayerData playerData = new PlayerData(name);
					playerData.setJoinDate(joinDate);
					WelcomeCore.newPlayerCache.put(name, playerData);
					// 广播欢迎语
					WelcomeCore.broadcastWelcome(name);
				} else if ("Welcomed".equals(msg)) {
					String welcomee = msgIn.readUTF();
					String welcomer = msgIn.readUTF();
					PlayerData playerData = WelcomeCore.newPlayerCache.get(welcomee);
					if (playerData != null) playerData.getWelcomed().add(welcomer);
				}
			} catch (IOException e) {
				e.printStackTrace();
				Welcome.getInstance().getLogger().info(" ");
				Welcome.getInstance().getLogger().info("[Welcome]An error occurred while reading bungeeCord message.".replace("&", "§"));
				Welcome.getInstance().getLogger().info(" ");
			}
		}
	}

}
